<template>
  <div class="reservation-setting-container">
    <el-card class="setting-card">
      <template #header>
        <div class="card-header">
          <span>预订桌位设置</span>
        </div>
      </template>

      <!-- 主开关控制 -->
      <div class="main-switch">
        <el-switch
            v-model="reservationEnabled"
            active-text="已开启预定餐桌预订业务"
            inactive-text="已关闭预定设置业务(关闭后用户将无法预定桌位)"
            @change="handleMainSwitchChange"
        />
      </div>

      <!-- 预定设置表单 -->
      <div v-if="reservationEnabled" class="setting-form">
        <el-form :model="form" label-width="180px">
          <el-form-item label="可预定日期">
            <el-input-number
                v-model="form.reservationDays"
                :min="1"
                :max="30"
                controls-position="right"
            />
            <span class="unit-text">天内</span>
          </el-form-item>

          <el-form-item label="保留时间">
            <el-input-number
                v-model="form.holdTime"
                :min="10"
                :max="120"
                controls-position="right"
            />
            <span class="unit-text">分钟</span>
          </el-form-item>

          <el-form-item label="提前锁定餐桌时间">
            <el-input-number
                v-model="form.lockTime"
                :min="10"
                :max="120"
                controls-position="right"
            />
            <span class="unit-text">分钟</span>
          </el-form-item>

          <el-form-item label="预约到店提醒时间">
            <el-input-number
                v-model="form.reminderTime"
                :min="10"
                :max="120"
                controls-position="right"
            />
            <span class="unit-text">分钟</span>
          </el-form-item>

          <!-- 可预定时间段 -->
          <el-form-item label="可预定时间段">
            <el-button
                type="primary"
                size="small"
                @click="handleAddTimeSlot"
            >
              添加预定时间
            </el-button>
            <div class="time-slots">
              <el-tag
                  v-for="(slot, index) in form.timeSlots"
                  :key="index"
                  closable
                  @close="handleRemoveTimeSlot(index)"
              >
                {{ slot }}
              </el-tag>
            </div>
          </el-form-item>

          <!-- 可预定桌台 -->
          <el-form-item label="可预定桌台">
            <el-button
                type="primary"
                size="small"
                @click="handleAddTableDialog"
            >
              添加预定桌台
            </el-button>

            <el-table
                :data="form.reservableTables"
                border
                style="width: 100%; margin-top: 10px;"
            >
              <el-table-column prop="location" label="桌位" width="120" />
              <el-table-column prop="type" label="桌型" width="150" />
              <el-table-column prop="numbers" label="桌号" />
              <el-table-column label="操作" width="120">
                <template #default="{row, $index}">
                  <el-button size="small" @click="handleEditTable($index)">编辑</el-button>
                  <el-button size="small" type="danger" @click="handleRemoveTable($index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>

          <!-- 底部按钮 -->
          <el-form-item class="form-footer">
            <el-button @click="handleCancel">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 添加/编辑桌台对话框 -->
    <el-dialog
        v-model="tableDialogVisible"
        :title="tableDialogTitle"
        width="50%"
    >
      <el-form :model="tableForm" label-width="100px">
        <el-form-item label="桌位">
          <el-select v-model="tableForm.location" placeholder="请选择桌位">
            <el-option
                v-for="loc in locationOptions"
                :key="loc.value"
                :label="loc.label"
                :value="loc.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="桌型">
          <el-select v-model="tableForm.type" placeholder="请选择桌型">
            <el-option
                v-for="type in tableTypeOptions"
                :key="type.value"
                :label="type.label"
                :value="type.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="桌号">
          <el-select
              v-model="tableForm.numbers"
              multiple
              filterable
              allow-create
              placeholder="请选择或输入桌号"
          >
            <el-option
                v-for="num in tableNumberOptions"
                :key="num"
                :label="num"
                :value="num"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="tableDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleTableConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加时间对话框 -->
    <el-dialog
        v-model="timeDialogVisible"
        title="添加预定时间"
        width="30%"
    >
      <el-time-picker
          v-model="newTimeSlot"
          format="HH:mm"
          value-format="HH:mm"
          placeholder="选择时间"
      />

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="timeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleTimeConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'ReservationSetting',
  setup() {
    // 主开关状态
    const reservationEnabled = ref(false)

    // 表单数据
    const form = reactive({
      reservationDays: 7,
      holdTime: 30,
      lockTime: 15,
      reminderTime: 30,
      timeSlots: ['11:00', '11:30', '12:00', '17:30', '18:00'],
      reservableTables: [
        { location: '1F大厅', type: '大桌(5-6人)', numbers: '0010, 0001' },
        { location: '2F大厅', type: '小桌(3-4人)', numbers: '0003, 0009' }
      ]
    })

    // 从 localStorage 加载数据
    onMounted(() => {
      const savedSettings = localStorage.getItem('reservationSettings');
      if (savedSettings) {
        const settings = JSON.parse(savedSettings);
        reservationEnabled.value = settings.enabled;
        form.reservationDays = settings.reservationDays;
        form.holdTime = settings.holdTime;
        form.lockTime = settings.lockTime;
        form.reminderTime = settings.reminderTime;
        form.timeSlots = settings.timeSlots;
      }
    });

    // 桌台对话框相关
    const tableDialogVisible = ref(false)
    const tableDialogTitle = ref('添加预定桌台')
    const tableForm = reactive({
      location: '',
      type: '',
      numbers: []
    })
    const currentTableIndex = ref(-1)

    // 时间对话框相关
    const timeDialogVisible = ref(false)
    const newTimeSlot = ref('')

    // 下拉选项
    const locationOptions = [
      { value: '1F大厅', label: '1F大厅' },
      { value: '2F大厅', label: '2F大厅' },
      { value: 'VIP包间', label: 'VIP包间' }
    ]

    const tableTypeOptions = [
      { value: '大桌(5-6人)', label: '大桌(5-6人)' },
      { value: '小桌(3-4人)', label: '小桌(3-4人)' },
      { value: '中桌(4-5人)', label: '中桌(4-5人)' }
    ]

    const tableNumberOptions = ['0001', '0002', '0003', '0004', '0005', '0006', '0007', '0008', '0009', '0010']

    // 方法
    const handleMainSwitchChange = (val) => {
      if (val) {
        ElMessage.success('预定业务已开启')
      } else {
        ElMessageBox.confirm(
            '关闭后用户将无法预定桌位，确定要关闭吗?',
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
        ).then(() => {
          ElMessage.info('预定业务已关闭')
        }).catch(() => {
          reservationEnabled.value = true
        })
      }
    }

    const handleAddTimeSlot = () => {
      timeDialogVisible.value = true
      newTimeSlot.value = ''
    }

    const handleTimeConfirm = () => {
      if (newTimeSlot.value) {
        if (!form.timeSlots.includes(newTimeSlot.value)) {
          form.timeSlots.push(newTimeSlot.value)
          form.timeSlots.sort()
        } else {
          ElMessage.warning('该时间段已存在')
        }
        timeDialogVisible.value = false
      } else {
        ElMessage.warning('请选择时间')
      }
    }

    const handleRemoveTimeSlot = (index) => {
      form.timeSlots.splice(index, 1)
    }

    const handleAddTableDialog = () => {
      tableDialogTitle.value = '添加预定桌台'
      currentTableIndex.value = -1
      tableForm.location = ''
      tableForm.type = ''
      tableForm.numbers = []
      tableDialogVisible.value = true
    }

    const handleEditTable = (index) => {
      const table = form.reservableTables[index]
      tableDialogTitle.value = '编辑预定桌台'
      currentTableIndex.value = index
      tableForm.location = table.location
      tableForm.type = table.type
      tableForm.numbers = table.numbers.split(',').map(num => num.trim())
      tableDialogVisible.value = true
    }

    const handleTableConfirm = () => {
      if (!tableForm.location || !tableForm.type || tableForm.numbers.length === 0) {
        ElMessage.warning('请填写完整信息')
        return
      }

      const tableData = {
        location: tableForm.location,
        type: tableForm.type,
        numbers: tableForm.numbers.join(', ')
      }

      if (currentTableIndex.value >= 0) {
        // 编辑现有桌台
        form.reservableTables.splice(currentTableIndex.value, 1, tableData)
      } else {
        // 添加新桌台
        form.reservableTables.push(tableData)
      }

      tableDialogVisible.value = false
    }

    const handleRemoveTable = (index) => {
      ElMessageBox.confirm(
          '确定要删除该预定桌台吗?',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
      ).then(() => {
        form.reservableTables.splice(index, 1)
        ElMessage.success('删除成功')
      }).catch(() => {
        ElMessage.info('已取消删除')
      })
    }

    const handleSubmit = () => {
      const settings = {
        enabled: reservationEnabled.value,
        reservationDays: form.reservationDays,
        holdTime: form.holdTime,
        lockTime: form.lockTime,
        reminderTime: form.reminderTime,
        timeSlots: form.timeSlots
      };

      // 保存到 localStorage
      localStorage.setItem('reservationSettings', JSON.stringify(settings));

      ElMessage.success('设置保存成功');
    }

    const handleCancel = () => {
      ElMessageBox.confirm(
          '确定要取消所有更改吗?',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
      ).then(() => {
        ElMessage.info('已取消更改')
        // 这里应该是重置表单或返回上一页
      }).catch(() => {
        ElMessage.info('继续编辑')
      })
    }

    return {
      reservationEnabled,
      form,
      tableDialogVisible,
      tableDialogTitle,
      tableForm,
      timeDialogVisible,
      newTimeSlot,
      locationOptions,
      tableTypeOptions,
      tableNumberOptions,
      handleMainSwitchChange,
      handleAddTimeSlot,
      handleTimeConfirm,
      handleRemoveTimeSlot,
      handleAddTableDialog,
      handleEditTable,
      handleTableConfirm,
      handleRemoveTable,
      handleSubmit,
      handleCancel
    }
  }
}
</script>

<style scoped>
.reservation-setting-container {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.setting-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.main-switch {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.setting-form {
  padding: 0 20px;
}

.unit-text {
  margin-left: 10px;
  color: #666;
}

.time-slots {
  margin-top: 10px;
}

.time-slots .el-tag {
  margin-right: 10px;
  margin-bottom: 10px;
}

.form-footer {
  margin-top: 30px;
  display: flex;
  justify-content: flex-end;
}

.el-button {
  margin-left: 10px;
}
</style>